import {
  Dimensions,
  Image,
  ImageSourcePropType,
  ScrollView,
  StyleSheet,
  Text,
  View,
} from "react-native";
import React, { Key, useEffect, useState } from "react";
import Head from "../../components/Head";
import RecommendList from "../../components/RecommendList";
import ImageView from "react-native-image-viewing";
import { useRoute } from "@react-navigation/native";
import { Https } from "../../api";
import { goodsDetail } from "../../types";
import Swiper from "react-native-swiper";
import ImageListAuto from "../../components/ImageListAout";
import { SafeAreaView } from "react-native-safe-area-context";
import { AntDesign } from "@expo/vector-icons";
import CartPopup from "../../components/CartPopup";
import { TouchableOpacity } from "react-native-gesture-handler";
import { Button } from "react-native-paper";
import { styleAll } from "../../styleAll";
const width = Dimensions.get("window").width;
type ProductDetailsPropsType = {
  goodsId: string;
  goodsColor: string;
};

const ProductDetails = () => {
  const router = useRoute();
  const [goodsDetail, setGoodsDetail] = useState<goodsDetail>();
  const [goodsStock, setGoodsStock] = useState<object>({}) as any;
  const { goodsColor, goodsId } = router.params as ProductDetailsPropsType;
  const [showImg, setShowImg] = useState([]);
  const [visible, setVisible] = useState(false);
  const [show, setShow] = useState(false);
  const [showIndex, setShowIndex] = useState(0);
  const [cartType, setCartType] = useState("");
  // const [goodsCode, setGoodsCode] = useState<string>("");
  // const [gsColorCode, setGsColorCode] = useState<string>("");
  const slideshow = [
    {
      uri: `https://cdn.bestseller.com.cn/goodsImagePC/ONLY/${goodsId}/${goodsColor}/750750/${goodsColor}_T01.jpg`,
    },
    {
      uri: `https://cdn.bestseller.com.cn/goodsImagePC/ONLY/${goodsId}/${goodsColor}/750750/${goodsColor}_T02.jpg`,
    },
    {
      uri: `https://cdn.bestseller.com.cn/goodsImagePC/ONLY/${goodsId}/${goodsColor}/750750/${goodsColor}_T03.jpg`,
    },
    {
      uri: `https://cdn.bestseller.com.cn/goodsImagePC/ONLY/${goodsId}/${goodsColor}/750750/${goodsColor}_T04.jpg`,
    },
    {
      uri: `https://cdn.bestseller.com.cn/goodsImagePC/ONLY/${goodsId}/${goodsColor}/750750/${goodsColor}_T05.jpg`,
    },
  ];
  const RecommendListConfig = {
    sceneId: "xqy103",
    returnCount: 30,
    sceneType: 2,
    sourceId: 31,
    itemId: goodsId,
  };

  useEffect(() => {
    getGoodsDetail();
    console.log(slideshow);
  }, []);
  //获取商品数据详情
  const getGoodsDetail = async () => {
    try {
      const result = await Promise.all([
        Https.goodsDetail({
          goodsCode: goodsId,
        }),
        Https.goodsStock({
          goodsCode: goodsId,
          type: 0,
        }),
      ]);
      result.forEach(({ success, data }, index) => {
        if (success) {
          //   if (!index) {
          //     const { color } = data;
          //     setColorList(color);
          //     changeSelect(data.projectCode, gsColorCode, color);
          //   }
          if (index) {
            setGoodsStock(data);
            return;
          }
          setShowImg(JSON.parse(data?.reminderPcen));
          setGoodsDetail(data);
          console.log(data);
        }
      });
    } catch (error) {
      alert("商品信息获取失败" + error);
    }
  };
  const hideModal = () => {
    setVisible(false);
    // setScrollEnabled(true);
  };
  const handleViewing = (index: number) => {
    setShowIndex(index);
    setShow(true);
  };

  const handleVisible = (type: string) => {
    setCartType(type);
    setVisible(true);
  };
  return (
    // <View style={{flex:1}}>

    <SafeAreaView style={{ backgroundColor: "#fff", flex: 1 }}>
      <Head />
      <ScrollView
        style={{ minHeight: 800, position: "relative" }}
        showsVerticalScrollIndicator={false}
        keyboardDismissMode={"on-drag"}
      >
        <Swiper
          style={styles.wrapper}
          autoplay={true}
          activeDot={<View style={styles.activeDot} />}
        >
          {slideshow &&
            slideshow.map(({ uri }, index) => (
              <TouchableOpacity
                activeOpacity={0.8}
                style={{ height: 400 }}
                onPress={() => handleViewing(index)}
                 key={uri}
              >
                <View style={styles.slide}>
                  <Image
                    style={{ height: 400, width: "100%" }}
                    source={
                      {
                        uri,
                      } as ImageSourcePropType
                    }
                  />
                </View>
              </TouchableOpacity>
            ))}
        </Swiper>

        <Text style={styles.ProductDetailsName}>
          {goodsDetail?.goodsName || "--"}
        </Text>
        <View style={styles.ProductContentPrice}>
          {goodsDetail?.color[0]?.discount !== 1 && (
            <Text style={styles.ProductContentDiscount}>
              {goodsDetail && (goodsDetail?.color[0]?.discount * 10).toFixed(1)}
              折
            </Text>
          )}
          <Text style={{ fontSize: 16 }}>
            ￥ {goodsDetail?.color[0]?.price}
          </Text>
          {goodsDetail?.color[0]?.discount !== 1 && (
            <Text style={styles.discount}>
              ￥{goodsDetail?.color[0]?.originalPrice}
            </Text>
          )}
        </View>
        <Text style={styles.ProductCode}>商品款号：{goodsId}</Text>
        <TouchableOpacity
          activeOpacity={0.8}
          onPress={() => handleVisible("addCart")}
        >
          <View style={styles.ProductSize}>
            <View style={styles.ProductTop}>
              <Text>选择 颜色分类 尺码</Text>
              <AntDesign name="right" size={19} color="#a2a2a2" />
            </View>
            <View style={styles.ProductColor}>
              {goodsDetail?.color.map(({ colorCode }) => (
                <Image
                  style={{ height: 50, width: 30, marginRight: 8 }}
                  source={
                    {
                      uri: `https://cdn.bestseller.com.cn/goodsImagePC/ONLY/${goodsId}/${colorCode}/108178/${colorCode}_p3.jpg`,
                    } as ImageSourcePropType
                  }
                />
              ))}
              <Text style={styles.ProductColorCount}>
                共有{goodsDetail?.color.length}种颜色可选择
              </Text>
            </View>
          </View>
        </TouchableOpacity>

        {showImg &&
          showImg.map(({ key, webUrl }) => (
            <ImageListAuto key={key} imgUrl={webUrl} />
          ))}

        <RecommendList {...RecommendListConfig} />
      </ScrollView>

      <ImageView
        images={slideshow}
        imageIndex={showIndex}
        visible={show}
        onRequestClose={() => setShow(false)}
      />
      <View style={{ ...styles.BottomModules }}>
        <Button
          color={"#fff"}
          mode="contained"
          buttonColor={"#d4d4d4"}
          textColor={"#000"}
          compact={true}
          style={{ borderRadius: 0 }}
          labelStyle={{ fontSize: 18 }}
          contentStyle={{ ...styles.BottomButton, ...styleAll.iosBottom }}
          onPress={() => handleVisible("addCart")}
        >
          购物车
        </Button>
        <Button
          mode="contained"
          buttonColor={"#000"}
          textColor={"#fff"}
          compact={true}
          style={{ borderRadius: 0 }}
          labelStyle={{ fontSize: 18 }}
          contentStyle={{ ...styles.BottomButton, ...styleAll.iosBottom }}
          onPress={() => handleVisible("purchase")}
        >
          立即购买
        </Button>
      </View>
      <CartPopup
        visible={visible}
        hideModal={hideModal}
        goodsCode={goodsId}
        gsColorCode={goodsColor}
        type={cartType}
      ></CartPopup>
    </SafeAreaView>
    // </View>
  );
};

export default ProductDetails;

const styles = StyleSheet.create({
  wrapper: {
    height: 400,
  },
  slide: {
    flex: 1,
    justifyContent: "center",
    alignItems: "center",
  },
  activeDot: {
    backgroundColor: "#fff",
    height: 8,
    width: 8,
    borderRadius: 999,
    marginHorizontal: 3,
  },
  ProductDetailsName: {
    paddingVertical: 10,
    fontSize: 19,
    textAlign: "center",
    fontWeight: "600",
  },
  ProductContentPrice: {
    width: "70%",
    marginLeft: "15%",
    flexDirection: "row",
    alignItems: "center",
    justifyContent: "space-evenly",
  },
  discount: {
    textDecorationLine: "line-through",
    color: "#929090",
    fontSize: 16,
  },
  ProductContentDiscount: {
    padding: 2,
    borderRadius: 3,
    fontSize: 15,
    color: "#fff",
    backgroundColor: "red",
  },
  ProductCode: {
    color: "#949494",
    textAlign: "center",
    paddingVertical: 5,
  },
  ProductSize: {
    marginTop: 10,
    padding: 20,
    borderTopWidth: 1,
    borderBottomWidth: 1,
    borderTopColor: "#ccc",
    borderBottomColor: "#ccc",
  },
  ProductTop: {
    display: "flex",
    flexDirection: "row",
    justifyContent: "space-between",
    paddingBottom: 5,
  },
  ProductColor: {
    display: "flex",
    flexDirection: "row",
    alignItems: "center",
  },
  ProductColorCount: {
    borderRadius: 3,
    padding: 2,
    color: "#949494",
    backgroundColor: "#e5e5e5",
  },
  BottomModules: {
    position: "absolute",
    bottom: 0,
    display: "flex",
    flexDirection: "row",
    width: "100%",
    backgroundColor: "#ccc",
  },
  BottomButton: {
    width: width / 2,
  },
});
